package com.example.yucheng.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {
    public static String SECRET="1fioewro3sfj";

    //生产token
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,2);//默认两小时过期

        builder.withExpiresAt(instance.getTime());
        String token=builder.sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    //验证token是否有效
    public static DecodedJWT verfy(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT;
    }

    //拿到token中的payload有效信息
    public static String getUid(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        String st=decodedJWT.getClaim("username").toString();
        return st;
    }
}
